﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DataModelWF
{
    public class DBHelper
    { 
        
        public string ConnStr = System.Configuration.ConfigurationManager.ConnectionStrings["LocalDBConnectionString"].ToString();
        public ConnPool pool;
        private SqlConnection conn;
        private SqlTransaction transaction;


        public DBHelper()
        {
            pool = ConnPool.getInstance();
            pool.setConnString(this.ConnStr);
        }

        public DBHelper(String connstr)
        {
            if (string.IsNullOrEmpty(connstr))
            {
                throw new Exception("连接数据库配置为空！");
            }
            this.ConnStr = connstr;
            pool = ConnPool.getInstance();
            pool.setConnString(connstr);
        }


        public DataSet Search(string sql)
        {
            DataSet ds = new DataSet();
            try
            {
                if (conn == null)
                {
                    conn = this.pool.getConnection();
                } 
                SqlDataAdapter dp = new SqlDataAdapter(sql, conn);
                dp.Fill(ds);
                 
            }catch(Exception ex)
            {
                return null;
            }
            return ds;
        }

        public void BeginTran()
        {
            if (conn == null)
            {
                conn = this.pool.getConnection();
            }
            transaction=conn.BeginTransaction();
        }


        public void RollbackTran()
        {
            if (transaction != null)
            {
                transaction.Rollback();
            }
             
        }


        public void Commit()
        {
            if (transaction != null)
            {
                transaction.Commit();
            }

        }
        public bool Query(string sql)
        {
            try
            {
                if (conn == null)
                {
                    conn = this.pool.getConnection();
                }
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = sql;
                if (transaction != null) { cmd.Transaction = transaction; }
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }


    }

}
